package com.dz.scrm.utils;

import android.util.Log;

import org.apache.http.ProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 查询手机号码归属地
 * @Author: 黄海
 * @CreateDate: 2021-5-12 17:04
 * @UpdateUser: 黄海
 * @UpdateDate: 2021-5-12 17:04
 * @UpdateRemark: 更新说明
 */
public class PhonePlaceUtils {

    //手机号码归属地查询
    public static Phone parsePhone(String phoneNumber) throws IOException, JSONException {
        String result = null;
        String url = "http://apis.juhe.cn/mobile/get";    //请求接口地址
        Map params = new HashMap();   //请求参数
        params.put("phone", phoneNumber);    //需要查询的手机号或手机号前7位
        params.put("key", "a77601ed6e5d3134e4e3aa406a193f6d");   //应用APPKEY（应用详细页查询）
        params.put("dtype", ""); //返回的数据格式，xml或者json，默认json
        Phone phone = new Phone();//将解析后的查询结果存储在phone中
        //获取查询所返回的结果
        result = queryPhonePlace(url, params, "GET");
        JSONObject object = new JSONObject(result);
        if (object.getInt("error_code") == 0) {
            JSONObject object1 = object.getJSONObject("result");
            if (object1.has("province")) {
                phone.setProvince((String) object1.get("province"));
            }
            if (object1.has("city")) {
                phone.setCity((String) object1.get("city"));
            }
            if (object1.has("company")) {
                phone.setCompany((String) object1.get("company"));
            }
        } else {
            Log.e("ActivityPhonePlace", "parsePhone: error_code" + object.get("error_code") + ":" + object.get("reason"));
        }
        return phone;
    }

    //手机号码归属地查询
    public static String parsePhoneAddress(String phoneNumber) {
        final String[] result = {null};
        final String[] address = {""};
        String url = "http://apis.juhe.cn/mobile/get";    //请求接口地址
        Map params = new HashMap();   //请求参数
        params.put("phone", phoneNumber);    //需要查询的手机号或手机号前7位
        params.put("key", "a77601ed6e5d3134e4e3aa406a193f6d");   //应用APPKEY（应用详细页查询）
        params.put("dtype", ""); //返回的数据格式，xml或者json，默认json
        Phone phone = new Phone();//将解析后的查询结果存储在phone中
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取查询所返回的结果
                try {
                    result[0] = queryPhonePlace(url, params, "GET");
                    JSONObject object = new JSONObject(result[0]);
                    if (object.getInt("error_code") == 0) {
                        JSONObject object1 = object.getJSONObject("result");
                        if (object1.has("province")) {
                            phone.setProvince((String) object1.get("province"));
                        }
                        if (object1.has("city")) {
                            phone.setCity((String) object1.get("city"));
                        }
                        if (object1.has("company")) {
                            phone.setCompany((String) object1.get("company"));
                        }
                        address[0] = phone.getProvince() + phone.getCity();
                    } else {
                        Log.e("ActivityPhonePlace", "parsePhone: error_code" + object.get("error_code") + ":" + object.get("reason"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return address[0];
    }


    /**
     * 获取网络资源，通过接口地址获取手机号码归属地
     *
     * @param strUrl 请求接口地址
     * @param params 请求参数
     * @param method 请求方式
     * @return 查询到的结果，以Json形式返回
     * @throws IOException
     */
    public static String queryPhonePlace(String strUrl, Map params, String method) throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();//打开和URL之间的连接
            //设置请求方式
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            //设置通用请求属性
            conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36");
            conn.setUseCaches(false);
            conn.setConnectTimeout(2000);
            conn.setReadTimeout(2000);
            conn.setInstanceFollowRedirects(false);
            //建立实际的连接
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            //定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输入流和连接
        finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map类型转为请求参数类型
    public static String urlencode(Map<String, String> data) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
        }
        return sb.toString();
    }

    public static class Phone {

        private String province;
        private String city;
        private String company;

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getCompany() {
            return company;
        }

        public void setCompany(String company) {
            this.company = company;
        }
    }
}
